<template>
  <div class="page-container">
    <div class="page-header">
      <h2>业务类型管理</h2>
      <p>管理系统中的业务分类信息</p>
    </div>

    <!-- 工具栏 -->
    <div class="table-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新增业务类型
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData" stripe border>
      <el-table-column prop="typeName" label="类型名称" width="150" />
      <el-table-column prop="description" label="描述" min-width="200" />
      <el-table-column prop="isActive" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success' : 'danger'">
            {{ row.isActive ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
<!--          <el-button -->
<!--            :type="row.isActive ? 'warning' : 'success'" -->
<!--            link -->
<!--            @click="handleToggleStatus(row)"-->
<!--          >-->
<!--            {{ row.isActive ? '禁用' : '启用' }}-->
<!--          </el-button>-->
          <el-button type="danger" link @click="handleDelete(row)">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="formData.typeName" placeholder="请输入业务类型名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入业务类型描述" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-switch
            v-model="formData.isActive"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { 
  getBusinessTypes, 
  createBusinessType, 
  updateBusinessType, 
  deleteBusinessType,
  toggleBusinessTypeStatus
} from '@/api/businessTypes'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const submitLoading = ref(false)

// 弹窗相关
const dialogVisible = ref(false)
const dialogMode = ref('create') // create, edit
const formRef = ref()

// 表单数据
const formData = reactive({
  id: null,
  typeName: '',
  description: '',
  isActive: true
})

// 表单验证规则
const formRules = {
  typeName: [
    { required: true, message: '请输入业务类型名称', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return dialogMode.value === 'create' ? '新增业务类型' : '编辑业务类型'
})

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 获取表格数据
const getTableData = async () => {
  try {
    loading.value = true
    const response = await getBusinessTypes()
    if (response.code === 200) {
      // 修复：后端返回的数据结构是 { data: [...], total: 10, page: 1, size: 10 }
      let responseData = response.data
      if (responseData && responseData.data && Array.isArray(responseData.data)) {
        tableData.value = responseData.data
        console.log('成功加载业务类型数据:', responseData.data.length, '条')
      } else if (responseData && Array.isArray(responseData)) {
        tableData.value = responseData
      } else {
        console.warn('API返回的数据格式不正确:', responseData)
        tableData.value = []
      }
    }
  } catch (error) {
    console.error('获取业务类型列表失败:', error)
    // 使用模拟数据
    tableData.value = [
      { id: 1, typeName: '销售业务', description: '产品销售相关业务', isActive: true, createdAt: '2024-01-01 10:00:00' },
      { id: 2, typeName: '技术服务', description: '技术支持和服务业务', isActive: true, createdAt: '2024-01-01 10:01:00' },
      { id: 3, typeName: '咨询服务', description: '咨询和顾问服务', isActive: true, createdAt: '2024-01-01 10:02:00' },
      { id: 4, typeName: '售后服务', description: '售后支持和维护服务', isActive: true, createdAt: '2024-01-01 10:03:00' },
      { id: 5, typeName: '培训服务', description: '产品培训和用户培训', isActive: false, createdAt: '2024-01-01 10:04:00' }
    ]
  } finally {
    loading.value = false
  }
}

// 新增
const handleCreate = () => {
  dialogMode.value = 'create'
  resetFormData()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogMode.value = 'edit'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    await toggleBusinessTypeStatus(row.id, !row.isActive)
    ElMessage.success(`${row.isActive ? '禁用' : '启用'}成功`)
    getTableData()
  } catch (error) {
    console.error('切换状态失败:', error)
    ElMessage.error('操作失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除业务类型"${row.typeName}"吗？`, '确认删除', {
      type: 'warning'
    })
    
    await deleteBusinessType(row.id)
    ElMessage.success('删除成功')
    getTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitLoading.value = true
    
    if (dialogMode.value === 'create') {
      await createBusinessType(formData)
      ElMessage.success('新增成功')
    } else {
      await updateBusinessType(formData.id, formData)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    getTableData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    typeName: '',
    description: '',
    isActive: true
  })
}

// 页面初始化
onMounted(() => {
  getTableData()
})
</script>

<style lang="scss" scoped>
.page-header {
  margin-bottom: 20px;
  
  h2 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }
  
  p {
    color: #666;
    font-size: 14px;
  }
}
</style>
